<?php
namespace app\common\helper;

use app\admin\controller\groupon\Config;
use app\admin\model\groupon\Store;
use app\common\model\Address;
use GuzzleHttp\Client;
use App\Api\PrinterService;
use App\Api\PrintService;
use App\Config\YlyConfig;
use App\Oauth\YlyOauthClient;
use think\exception\HttpResponseException;
use think\Log;

class Printer
{
    protected $appid;
    protected $key;
    protected $config;
    protected $client;
    protected $token;
    protected $m_code;
    public function __construct()
    {
        $config = cache('config');
        $this->key = $config['client_key'];
        $this->appid = $config['client_id'];
        $this->m_code = $config['print_code'];
        $this->config = new YlyConfig($this->appid,$this->key);
        $this->client = new YlyOauthClient($this->config);
    }


    public function getToken()
    {
        $this->token = cache('printer_access_token');
        if (!$this->token) {
            $this->token = $this->client->getToken();
            cache('printer_access_token',$this->token);
        }
        return $this;
    }

    // 下单自动打印，需在后台第三方设置开启打印功能
    public function printer($order)
    {
        $c = cache('config');
        $address = Address::where('id',$order->address_id)->find();
        $create_time = $order['create_time'];
        $html = "<MS>1,3</MS>\r";
        $html .= "<FH><FW> ** {$c['web_name']} ** </FW> </FH>\r\r";
        $html .= "................................\r";
//        $html .= "<FH><center>{$store['name']}</center> </FH>\r";
        $html .= "下单时间：{$create_time}\r";
        $html .= "单号：{$order['order_no']}\r";
        $html .= "*************商品***************\r";
        foreach ($order['item'] as $item) {
            $goods = $item['content']['goods'];
            $goods_item = $item['content']['goods_item'];
            $title2 = '默认';
            if ($goods['is_single'] == 2) {
                $title2 = $goods_item['title'];
            }
            $html .= $goods['title'] ."({$title2})" ."  " . $item['num'] . "  ￥" . $item['money'] . "\r";
        }

        $html .= "******************************\r";
        $html .= "<FH>订单总价：￥{$order['money']}\r";
        $remark = empty($order['content']) ? '无' : $order['content'];
        $html .= "订单备注：". $remark . "\r";
        $html .= "收件人：". strReplaceStar($address->getData('name')) . "\r";
        $html .= "电话：". $address->getData('tel') . "\r";
        $html .= "地址：". $address->getData('address') . "\r";
        $html .= "</FH><FH2><FS><FW2> ** 完 **</FW2></FS></FH2>";
        $this->getToken();
        try {
            $print = new PrintService($this->token->access_token,$this->config);
            $data = $print->index($this->m_code,$html,$order['order_no']);
        } catch (\Exception $e) {
            file_put_contents('print.txt','printError-'.$e->getMessage() . "\r\n",FILE_APPEND);
        }
    }

    // 接收云端推送打印状态接口
    public function setStatus($data)
    {
        file_put_contents("print.txt",json_encode($data)."\r\n",FILE_APPEND);
        if ($data['cmd'] == "print_status") {
            if (empty($data['machine_code']) || empty($data['online'])) {
                return false;
            }
            Store::update(['printer_status'=>$data['online']],['machine_code'=>$data['machine_code']]);
        }
        return true;
    }

    // 打印二维码
    public function printerQrcode($data)
    {
        $qrData = [
            "purchase_id" => $data['purchase_id'],
            "goods_id" => $data['goods_id'],
            "sku_id" => $data['sku_id'],
        ];
        $html = "<QR>".json_encode($qrData)."</QR>\r";
        $html .= "{$data['goods_text']}\r ";
        if (!empty($data['sku_text'])) {
            $html .= "{$data['sku_text']}\r ";
        }
        $html .= "******************************\r";

        try {
            $this->getToken();
            $sn = time() . rand(10000,99999);
            $print = new PrintService($this->token->access_token,$this->config);
            $data = $print->index($this->printConfig['machine_code'],$html,md5($sn));
            return true;
        } catch (\Exception $e) {
            file_put_contents('print.txt',"error".$e->getMessage() . "\r\n",FILE_APPEND);
            return  $e->getMessage();
        }
    }
}